package com.zcsy.manage.web.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.manage.model.system.DistrictInfo;
import com.zcsy.manage.service.system.IDistrictInfoService;

/**
 * @Title: DistrictInfoController.java
 * @Package： com.zcsy.shop.web.common 
 * @Description: 区域信息控制器
 *
 * @author caiyinli 13277030520@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2015年7月14日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/district")
public class DistrictInfoController {

    private static final int PAGE_SIZE =  10; //每页大小
    private static final int PAGE_NO   =  1;  //默认首页
    private static final int ALL_LEVEL = -1;  //所有地区等级
    private static final int ALL_STATE = -1;  //所有地区状态
    private static final int STATE     = 0;   //默认新增状态为0：停用
    private static final int INIT_LEVEL     = -1;   //初始化区域等级
    private static final int INIT_STATE     = -1;   //初始化区域状态
    private static final int FIRST_LEVEL    = 1;   //一级区域等级
    private static final int SECOND_LEVEL   = 2;   //二级区域 等级
    private static final int THIRD_LEVEL    = 3;   //三级区域等级
    
    @Autowired 
    private IDistrictInfoService districtInfoService;
    
    
    /**
     * @Description 根据关键字搜索区域信息<br>
     * 
     * @param pNo 当前页码
     * @param postCode 区域编码
     * @param regionName 区域名称
     * @param level 区域级别
     * @param state 状态
     * @param req 用户请求
     * @return 返回区域列表页面
     * @author caiyinli 13277030520@163.com
     * @date 2015年7月14日
     * @see 
     */
    
    @RequestMapping(value="districtList" , method = RequestMethod.GET)
    public String districtList(Model model, Integer pNo, String postCode, String regionName, Integer level,
         Integer state,  HttpServletRequest req){
    	
	    if(pNo == null){
            pNo = PAGE_NO;
        }
	    
	    if(level == null){
	    	level = INIT_LEVEL;
	    }
	    
	    if(state == null){
	    	state = INIT_STATE;
	    }
	    
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, PAGE_SIZE);
        
        DistrictInfo districtInfo = new DistrictInfo();
        
        if(StringUtils.isNotEmpty(postCode)){
            districtInfo.setPostCode(postCode);
        }
        if(StringUtils.isNotEmpty(regionName)){
            districtInfo.setRegionName(regionName);
        }
        if(level != ALL_LEVEL){
            districtInfo.setRegionLevel(level);
        }
        if(state != ALL_STATE){
            districtInfo.setState(state);
        }
        
        List<DistrictInfo> districtInfos = districtInfoService.getDistrictInfoByKeyWord(districtInfo);
        PageInfo<DistrictInfo> info = new PageInfo<DistrictInfo>(districtInfos);
        
		model.addAttribute("districtInfo", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("postCode", postCode);
		model.addAttribute("regionName", regionName);
		model.addAttribute("level", level);
		model.addAttribute("state", state);
        
        return "system/district/districtList";
    }
    
    /**
     * @Description 根据区域级别获取区域信息列表<br>
     * 
     * @param level 区域级别
     * @param req 用户请求
     * @return 区域信息列表
     * @author caiyinli 13277030520@163.com
     * @date 2015年7月14日
     * @see 
     */
	@RequestMapping(value="/districtByLevel" , method = RequestMethod.POST)
	@ResponseBody
    public List<DistrictInfo> districtByLevel( int level, HttpServletRequest req){
			
		List<DistrictInfo> list = districtInfoService.getDistrictInfoByLevel(level); 
			
        return list;
    }
    

	/**
	 * @Description 编辑和保存方法<br>
	 * 
	 * @param postCode 邮编
	 * @param regionName 区域名称
	 * @param level 区域等级
	 * @param id 主键id
	 * @param parentId 上级区域id
	 * @return 返回RequestJson
	 * @author caiyinli 13277030520@qq.com
	 * @date 2016年1月14日
	 * @see 
	 */
	@RequestMapping(value="saveOrUpdate" , method = RequestMethod.POST)
	@ResponseBody
    public RequestJson saveOrUpdate(String postCode,String regionName,int level,int id,int parentId){
		
        RequestJson result = new RequestJson();
        try {
        	DistrictInfo districtInfo = new DistrictInfo();
        	districtInfo.setPostCode(postCode);
        	districtInfo.setRegionName(regionName);
        	districtInfo.setRegionLevel(level);
        	districtInfo.setId(id);
        	districtInfo.setParentId(parentId);
        	
        	if(districtInfo != null && districtInfo.getId() != 0){
        		districtInfoService.saveOrUpdateDistrictInfo(districtInfo);
        	}else{
        		districtInfo.setState(STATE);
        		districtInfoService.insert(districtInfo);
        	}
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * @Description 根据区域信息id可以同时删除多条区域信息<br>
     * 
     * @param ids 区域信息对象id数组
     * @param req 用户请求
     * @return 删除结果RequestJson
     * @author caiyinli 13277030520@163.com
     * @date 2015年7月14日
     * @see 
     */
	@RequestMapping(value="deleteByPrimaryKeys" , method = RequestMethod.POST)
	@ResponseBody
    public RequestJson deleteByPrimaryKeys(@RequestParam(value="ids[]")int[] ids,HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
        	int len = ids.length;
        	Integer[] iarr = new Integer[len];
        	for(int i = 0;i < len;i++){
        		iarr[i] = Integer.valueOf(ids[i]);
        	}
          int flag = districtInfoService.deleteByPrimaryKeys(iarr);
          if(flag == Constants.SQL_RESULT_ERROR){
              result.setMsg("删除区域中包含有子区域");
              result.setSuccess(false);
          }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("删除失败");
            result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * @Description 更新区域信息状态<br>
     * 切换状态时，需判断是否有子集，如果有自己，不修改状态，返回错误提示到前端<br>
     * 
     * @param id 主键id
     * @param state 地区状态 0：停用  1：启用
     * @param req 用户请求
     * @return  修改结果RequestJson
     * @author caiyinli 13277030520@163.com
     * @date 2015年7月14日
     * @see 
     */
	@RequestMapping(value="updateState" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateState( int id, int state, HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
          int flag = Constants.SQL_RESULT_ERROR;
          	  flag = districtInfoService.updateDistrictInfoState(id, state);
          if(flag==Constants.SQL_RESULT_SUCCESS){
        	  result.setSuccess(true);
          }else{
        	  result.setMsg("停用区域中包含有子区域，请先停用子区域!");
        	  result.setSuccess(false);
          }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("停用失败");
            result.setSuccess(false);
        }
        return result;
    }
    
  
    /**
     * @Description 返回地区编辑或新增框<br>
     * 
     * @param model
     * @param id 主键id
     * @return 返回新增或编辑页面
     * @author caiyinli 13277030520@qq.com
     * @date 2016年1月14日
     * @see 
     */
    @RequestMapping(value = "selectById", method = RequestMethod.GET)
    public String selectById(Model model, int id) {
        try {
            if (id == Constants.STATE_DISABLED) {
                model.addAttribute("type", Constants.MENU_STATE_ENABLED);
                DistrictInfo districtInfo = new DistrictInfo();
                districtInfo.setRegionLevel(INIT_LEVEL);
                model.addAttribute("district",districtInfo);
            } else {
                DistrictInfo districtInfo = districtInfoService.getDistrictInfoById(id);
                model.addAttribute("district", districtInfo);
                DistrictInfo pInfo = districtInfoService.getDistrictInfoById(districtInfo.getParentId());
                model.addAttribute("pInfo", pInfo);
                List<DistrictInfo> listDistrict = new ArrayList<DistrictInfo>();
                if(districtInfo.getRegionLevel() == SECOND_LEVEL){
                	listDistrict = districtInfoService.getDistrictInfoByLevel(FIRST_LEVEL);
                }else if(districtInfo.getRegionLevel() == THIRD_LEVEL){
                	listDistrict = districtInfoService.getDistrictInfoByLevel(SECOND_LEVEL);
                }
                model.addAttribute("listDistrict", listDistrict);
                model.addAttribute("type", Constants.MENU_STATE_DISABLED);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "system/district/districtEdit";
    }
    
    /**
     * @Description 获取指定父名称的区域信息<br>
     * 
     * @param parentName 上级分类名称
     * @param req 用户请求
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2015年7月14日
     * @see 
     */
    @RequestMapping(value="/getDistrictInfoByParentName", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getDistrictInfoByParentName(String parentName, Integer level, HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
			List<DistrictInfo> districtInfos = districtInfoService.getDistrictInfoByParentName(parentName, level);
			result.setObj(districtInfos);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return result;
    }
    
    @RequestMapping(value="/getDistrictInfoByParentId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getDistrictInfoByParentId(Integer parentId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<DistrictInfo> districtInfos = districtInfoService.getDistrictInfoByParentId(parentId);
    		result.setObj(districtInfos);
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    	return result;
    }
}
